<?php
class CCharset
{

    public $gb_map;
    public $big5_map;
    public $dep_char = 127;

    public function CCharset( )
    {
        $path = dirname( __FILE__ );
        $this->gb_map = "{$path}/gb.map";
        $this->big5_map = "{$path}/big5.map";
    }

    public function cbig5_gb( $str, $fd )
    {
        $c = ord( substr( $str, 0, 1 ) );
        $x = ord( substr( $str, 1, 1 ) );
        $address = ( $c - 160 ) * 510 + ( $x - 1 ) * 2;
        fseek( $fd, $address );
        $hi = fgetc( $fd );
        $lo = fgetc( $fd );
        return $hi.$lo;
    }

    public function cgb_big5( $str, $fd )
    {
        $c = ord( substr( $str, 0, 1 ) );
        $x = ord( substr( $str, 1, 1 ) );
        $address = ( $c - 160 ) * 510 + ( $x - 1 ) * 2;
        fseek( $fd, $address );
        $hi = fgetc( $fd );
        $lo = fgetc( $fd );
        return $hi.$lo;
    }

    public function Big5_Gb( $str )
    {
        $fd = fopen( $this->gb_map, "r" );
        $str = str_replace( "charset=utf-8", "charset=gb2312", $str );
        $str = str_replace( "charset=utf-8", "charset=gb2312", $str );
        $outstr = "";
        $i = 0;
        while ( $i < strlen( $str ) )
        {
            $ch = ord( substr( $str, $i, 1 ) );
            if ( $this->dep_char < $ch )
            {
                $outstr .= $this->cbig5_gb( substr( $str, $i, 2 ), $fd );
                ++$i;
            }
            else
            {
                $outstr .= substr( $str, $i, 1 );
            }
            ++$i;
        }
        fclose( $fd );
        return $outstr;
    }

    public function Gb_Big5( $str )
    {
        $fd = fopen( $this->big5_map, "r" );
        $str = str_replace( "charset=gb2312", "charset=utf-8", $str );
        $outstr = "";
        $i = 0;
        while ( $i < strlen( $str ) )
        {
            $ch = ord( substr( $str, $i, 1 ) );
            if ( $this->dep_char < $ch )
            {
                $outstr .= $this->cgb_big5( substr( $str, $i, 2 ), $fd );
                ++$i;
            }
            else
            {
                $outstr .= substr( $str, $i, 1 );
            }
            ++$i;
        }
        fclose( $fd );
        return $outstr;
    }

}

?>